package cn.edu.ncu.housinghub.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Service
@RequiredArgsConstructor
public class OSSService {
    private final OSS ossClient;

    @Value("${oss.bucketName}")
    private String bucketName;

    @Value("${oss.endpoint}")
    private String endpoint;

    public String uploadFile(MultipartFile file, String filePath) {
        try {
            InputStream inputStream = file.getInputStream();

            // 1. 创建文件元数据对象，配置预览相关的 HTTP 头
            ObjectMetadata metadata = new ObjectMetadata();

            // 2. 设置 Content-Type（根据文件类型自动识别或手动指定）
            String contentType = file.getContentType();
            if (contentType == null) {
                // 若无法自动识别，根据文件路径后缀手动设置
                if (filePath.endsWith(".pdf")) {
                    contentType = "application/pdf";
                } else if (filePath.endsWith(".jpg") || filePath.endsWith(".jpeg")) {
                    contentType = "image/jpeg";
                } else if (filePath.endsWith(".png")) {
                    contentType = "image/png";
                } else if (filePath.endsWith(".gif")) {
                    contentType = "image/gif";
                } else if (filePath.endsWith(".bmp")) {
                    contentType = "image/bmp";
                }
            }
            metadata.setContentType(contentType);

            // 3. 设置 Content-Disposition: inline（预览），处理中文文件名乱码
            String originalFilename = file.getOriginalFilename();
            if (originalFilename != null) {
                String encodedFileName = URLEncoder.encode(originalFilename, StandardCharsets.UTF_8.name());
                metadata.setContentDisposition("inline; filename=\"" + encodedFileName + "\"");
            }

            // 4. 上传文件（传入配置好的元数据）
            ossClient.putObject(bucketName, filePath, inputStream, metadata);

            // 5. 拼接预览 URL
            return "https://" + bucketName + "." + endpoint + "/" + filePath;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }
}